package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private String method,uri,protocol;
    private Map<String,String> headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;

        parseRequestLine();
        parseHeaders();
        parseContent();
    }

    private void parseRequestLine() throws IOException {
        String line = readLine();
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];

    }

    private void parseHeaders() throws IOException {
        while (true){
            String line = readLine();
            if(line.isEmpty())break;
            String[] data = line.split(":\\s");
            headers.put(data[0],data[1]);
        }


    }

    private void parseContent(){

    }

    private String readLine() throws IOException {
        int a;
        char per = 'a',cur;
        StringBuilder line = new StringBuilder();
        InputStream in = socket.getInputStream();
        while (true){
            a = in.read();
            cur = (char) a;
            line.append(cur);
            if(cur == 10 && per == 13)break;
            per = cur;
        }
        return line.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }
}
